package xyz.xuminghai.javafx_learn.scene.control;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.scene.Scene;
import javafx.scene.control.ChoiceBox;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import javafx.util.StringConverter;

import java.util.List;

/**
 * 2023/1/17 9:44 星期二<br/>
 * <p>
 * ChoiceBox 用于向用户呈现一组相对较小的预定义选项，用户可以从中进行选择。
 * ChoiceBox 在“显示”时将向用户显示这些选项并允许他们准确地选择一个选项。不显示时，显示当前选择。
 *
 * @author xuMingHai
 */
public class ChoiceBoxApp extends Application {

    private final AnchorPane anchorPane = new AnchorPane();

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void init() {
        Student student1 = new Student("张三", 18);
        Student student2 = new Student("李四", 19);
        Student student3 = new Student("王五", 20);
        Student student4 = new Student("赵六", 30);

        ChoiceBox<Student> choiceBox = new ChoiceBox<>(FXCollections
                .observableArrayList(List.of(student1, student2, student3, student4)));

        // 设置转换器
        choiceBox.setConverter(new StringConverter<>() {
            @Override
            public String toString(Student student) {
                if (student == null) {
                    return "";
                }
                return student.name() + " - " + student.age();
            }

            @Override
            public Student fromString(String string) {
                return null;
            }
        });

        choiceBox.setOnAction(event -> System.out.println("choiceBox.getValue() = " + choiceBox.getValue()));

        anchorPane.getChildren().add(choiceBox);
    }

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle(getClass().getSimpleName());
        primaryStage.setScene(new Scene(anchorPane, 800, 600));
        primaryStage.show();
    }

    /**
     * 学生记录类
     *
     * @param name 姓名
     * @param age  年龄
     */
    private record Student(String name, int age) {
    }
}
